﻿$.fn.dataTableExt.oStdClasses.sWrapper = 'no-margin last-child';
$.fn.dataTableExt.oStdClasses.sInfo = 'message no-margin';
$.fn.dataTableExt.oStdClasses.sLength = 'float-left';
$.fn.dataTableExt.oStdClasses.sFilter = 'float-right';
$.fn.dataTableExt.oStdClasses.sPaging = 'sub-hover paging_';
$.fn.dataTableExt.oStdClasses.sPagePrevEnabled = 'control-prev';
$.fn.dataTableExt.oStdClasses.sPagePrevDisabled = 'control-prev disabled';
$.fn.dataTableExt.oStdClasses.sPageNextEnabled = 'control-next';
$.fn.dataTableExt.oStdClasses.sPageNextDisabled = 'control-next disabled';
$.fn.dataTableExt.oStdClasses.sPageFirst = 'control-first';
$.fn.dataTableExt.oStdClasses.sPagePrevious = 'control-prev';
$.fn.dataTableExt.oStdClasses.sPageNext = 'control-next';
$.fn.dataTableExt.oStdClasses.sPageLast = 'control-last';

$.fn.dataTableExt.oPagination.four_button = {
    "fnInit": function (oSettings, nPaging, fnCallbackDraw) {

        var nInput = document.createElement('select');
        nInput.style.display = "inline";

        nFirst = document.createElement('span');
        nPrevious = document.createElement('span');
        nNext = document.createElement('span');
        nLast = document.createElement('span');
        nDDL = document.createElement('span');

        nFirst.innerHTML += "<img src='/ODSYSUI/Content/Images/icons/fugue/control-double-180.png' width='16' height='16'>";
        nPrevious.innerHTML += "<img src='/ODSYSUI/Content/Images/icons/fugue/control-180.png' width='16' height='16'>";
        nNext.innerHTML += "<img src='/ODSYSUI/Content/Images/icons/fugue/control.png' width='16' height='16'>";
        nLast.innerHTML += "<img src='/ODSYSUI/Content/Images/icons/fugue/control-double.png' width='16' height='16'>";

        nFirst.className = "paginate_button first";
        nPrevious.className = "paginate_button previous";
        nNext.className = "paginate_button next";
        nLast.className = "paginate_button last";
        
        nPaging.appendChild(nFirst);
        nPaging.appendChild(nPrevious);
        nPaging.appendChild(nNext);
        nPaging.appendChild(nLast);
        nPaging.appendChild(nInput);

        $(nFirst).click(function () {
            oSettings.oApi._fnPageChange(oSettings, "first");
            fnCallbackDraw(oSettings);
        });

        $(nPrevious).click(function () {
            oSettings.oApi._fnPageChange(oSettings, "previous");
            fnCallbackDraw(oSettings);
        });

        $(nNext).click(function () {
            oSettings.oApi._fnPageChange(oSettings, "next");
            fnCallbackDraw(oSettings);
        });

        $(nLast).click(function () {
            oSettings.oApi._fnPageChange(oSettings, "last");
            fnCallbackDraw(oSettings);
        });

        $(nInput).change(function (e) { // Set DataTables page property and redraw the grid on listbox change event.
            window.scroll(0, 0); //scroll to top of page
            if (this.value === "" || this.value.match(/[^0-9]/)) { /* Nothing entered or non-numeric character */
                return;
            }
            var iNewStart = oSettings._iDisplayLength * (this.value - 1);
            if (iNewStart > oSettings.fnRecordsDisplay()) { /* Display overrun */
                oSettings._iDisplayStart = (Math.ceil((oSettings.fnRecordsDisplay() - 1) / oSettings._iDisplayLength) - 1) * oSettings._iDisplayLength;
                fnCallbackDraw(oSettings);
                return;
            }
            oSettings._iDisplayStart = iNewStart;
            fnCallbackDraw(oSettings);
        }); /* Take the brutal approach to cancelling text selection */
        $('span', nPaging).bind('mousedown', function () {
            return false;
        });
        $('span', nPaging).bind('selectstart', function () {
            return false;
        });

        /* Disallow text selection */
        $(nFirst).bind('selectstart', function () { return false; });
        $(nPrevious).bind('selectstart', function () { return false; });
        $(nNext).bind('selectstart', function () { return false; });
        $(nLast).bind('selectstart', function () { return false; });
    },


    "fnUpdate": function (oSettings, fnCallbackDraw) {
        if (!oSettings.aanFeatures.p) {
            return;
        }

        var iPages = Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength);
        var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1; /* Loop over each instance of the pager */
        var an = oSettings.aanFeatures.p;
        for (var i = 0, iLen = an.length; i < iLen; i++) {
            //var spans = an[i].getElementsByTagName('span');
            var inputs = an[i].getElementsByTagName('select');
            var elSel = inputs[0];
            var buttons = an[i].getElementsByTagName('span');

            if (elSel.options.length != iPages) {
                elSel.options.length = 0; //clear the listbox contents
                for (var j = 0; j < iPages; j++) { //add the pages
                    var oOption = document.createElement('option');
                    oOption.text = j + 1;
                    oOption.value = j + 1;
                    try {
                        elSel.add(oOption, null); // standards compliant; doesn't work in IE
                    } catch (ex) {
                        elSel.add(oOption); // IE only
                    }
                }
                //spans[1].innerHTML = " nbsp;of nbsp;" + iPages;
            }
            elSel.value = iCurrentPage;

            if (oSettings._iDisplayStart === 0) {
                buttons[0].className = "paginate_disabled_previous";
                buttons[1].className = "paginate_disabled_previous";
            }
            else {
                buttons[0].className = "paginate_enabled_previous";
                buttons[1].className = "paginate_enabled_previous";
            }

            if (oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()) {
                buttons[2].className = "paginate_disabled_next";
                buttons[3].className = "paginate_disabled_next";
            }
            else {
                buttons[2].className = "paginate_enabled_next";
                buttons[3].className = "paginate_enabled_next";
            }
        }
    }
};

$().ready(function () {

    $('.sortable').each(function (i) {
        // DataTable config
        var gridView = $(this),
            oTable = gridView.dataTable({
                /*
                 * We set specific options for each columns here. Some columns contain raw data to enable correct sorting, so we convert it for display
                 * @url http://www.datatables.net/usage/columns
                 */
                aoColumns: columnsCollection,

                //    [
                //    { bSortable: false },	// No sorting for this columns, as it only contains checkboxes
                //    { sType: 'string' },
                //    { sType: 'string' },
                //    {
                //        sType: 'numeric', bUseRendered: false, fnRender: function (obj) // Append unit and add icon
                //        {
                //            return '<small><img src="/ODSYSUI/Content/Images/icons/fugue/image.png" width="16" height="16" class="picto"> ' + obj.aData[obj.iDataColumn] + ' Ko</small>';
                //        }
                //    },
                //    { sType: 'date' },
                //    {
                //        sType: 'numeric', bUseRendered: false, fnRender: function (obj) // Size is given as float for sorting, convert to format 000 x 000
                //        {
                //            return obj.aData[obj.iDataColumn].split('.').join(' x ');
                //        }
                //    },
                //    { bSortable: false }	// No sorting for actions column
                //],

                /*
                 * Set DOM structure for table controls
                 * @url http://www.datatables.net/examples/basic_init/dom.html
                 */
                sDom: '<"block-controls"<"controls-buttons"Tp>>rti<"block-footer clearfix"l>',

                /*
                 * Callback to apply template setup
                 */
                fnDrawCallback: function () {
                    this.parent().applyTemplateSetup();
                },
                fnInitComplete: function () {
                    this.parent().applyTemplateSetup();
                },

                "bPaginate": true,
                "bLengthChange": false,
                "bFilter": true, //Search
                "bSort": true,
                "bInfo": true,
                "bAutoWidth": true,
                "sPaginationType": "four_button", //"full_numbers", //"input",
                "oLanguage": {
                    "sLengthMenu": "Mostrando _MENU_ registros por página",
                    "sZeroRecords": "No se han encontrado registros.",
                    "sInfo": "Mostrando _START_ a _END_ de _TOTAL_ registros",
                    "sInfoEmpty": "Mostrando 0 a 0 de 0 registros",
                    "sInfoFiltered": "(filtrado desde _MAX_ registros totales)",
                    "sSearch": "Buscar"
                },
                "oTableTools": {
                    "sSwfPath": "/ODSYSUI/Content/Media/Swf/copy_csv_xls_pdf.swf",
                    "aButtons": [
                        {
                            "sExtends": "csv",
                            "sTitle": "csv"
                        },
                        {
                            "sExtends": "xls",
                            "sTitle": "xls"
                        },
                        {
                            "sExtends": "pdf",
                            "sTitle": "pdf"
                        }
                    ]
                }
            }).columnFilter({
                aoColumns: columnsFilterOrder
            });
        ;//.columnFilter({
        //    aoColumns: [
        //        null,
        //        { type: "text" },
        //        { type: "text" },
        //        { type: "text" },
        //        { type: "text" },
        //        { type: "text" },
        //        null
        //    ]
        //});

        // Sorting arrows behaviour
        gridView.find('thead .sort-up').click(function (event) {
            // Stop link behaviour
            event.preventDefault();

            // Find column index
            var column = $(this).closest('th'),
                columnIndex = column.parent().children().index(column.get(0));

            // Send command
            oTable.fnSort([[columnIndex, 'asc']]);

            // Prevent bubbling
            return false;
        });
        gridView.find('thead .sort-down').click(function (event) {
            // Stop link behaviour
            event.preventDefault();

            // Find column index
            var column = $(this).closest('th'),
                columnIndex = column.parent().children().index(column.get(0));

            // Send command
            oTable.fnSort([[columnIndex, 'desc']]);

            // Prevent bubbling
            return false;
        });
    });

});